#include <func.h>

#define MAXLINE 1024

int main(void)
{
    int fd_1 = open("pipe1", O_RDONLY);
    int fd_2 = open("pipe2", O_WRONLY);
    
    fd_set readfds;
    FD_ZERO(&readfds);
    FD_SET(STDIN_FILENO, &readfds);
    FD_SET(fd_1, &readfds);
    //FD_SET(fd_2, &readfds);

    char buffer[MAXLINE];
    printf("开始点对点聊天\n");
    while(1)
    {
        fd_set fds = readfds;
        int select_ret = select(4 + 1, &fds, NULL, NULL, NULL);
        switch(select_ret)
        {
        case -1:
            error(1, errno, "select");
        default:
            if(FD_ISSET(STDIN_FILENO, &fds))
            {
               if(fgets(buffer, MAXLINE, stdin) == NULL)
                   _exit(1);
               else
                write(fd_2, buffer, MAXLINE);
            }   
            else if(FD_ISSET(fd_1, &fds)) 
            {
                int ret = read( fd_1,buffer, MAXLINE);
                if(ret == 0)
                    _exit(0);
                printf("child :%s", buffer);
            }
        }
    }

    return 0;
}

